package com.spzx.common.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

/**
 * @author LOGIN
 * @title RabbitInitConfigApplicationListener
 * @create 2025/7/31 14:09
 * @description
 */
@Slf4j
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallback();
    }
    private void setupCallback(){
        /*
        * 只确认消息 是否正确到达Exchange中，成功与否都会回调
        *
        * @param correlation 相关数据  非消息本身业务数据
        * @param ack         应答结果
        * @param reason      如果发送消息到交换器失败，错误原因
        * */
        //消息确认机制
        rabbitTemplate.setConfirmCallback((correlationData,ack,reason) ->{
            if (ack){
                //消息到交换机成功
                log.info("消息发送到Exchange成功:{}",correlationData);
            }else {
                //消息发送到交换机失败
                log.error("消息发送到Exchange失败:{}",reason);
            }
        });
        /*
        * 消息没有正确到达队列时回调，如果正确到达队列不执行
        *
        * */
        rabbitTemplate.setMandatory(true);//是否让rabbitmq将失败的消息的信息再次返回给生产者 todo 可省略
        //消息回退机制
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("返回: " + returned.getMessage()
                    + "\n 响应码: " + returned.getReplyCode()
                    + "\n 响应消息: " + returned.getReplyText()
                    + "\n 交换机: " + returned.getExchange()
                    + "\n 路由: " + returned.getRoutingKey()
            );
        });
    }
}
